package org.itcast.travel.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.itcast.travel.exception.LikeNotAllowException;
import org.itcast.travel.mapper.CommentLikeInfoMapper;
import org.itcast.travel.mapper.CommentMapper;
import org.itcast.travel.pojo.Comment;
import org.itcast.travel.pojo.CommentLikeInfo;
import org.itcast.travel.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * wangcong
 * 2024/12/26 20:04
 */
@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public void insertOne(Comment comment) {
        comment.setCreateTime(LocalDateTime.now());
        commentMapper.insert(comment);
    }

    @Override
    public void deleteComment(int commentId) {
        // 删除该条评论以及对应回复这个评论的所有评论
//        commentMapper.deleteByPrimaryKey(commentId);
        commentMapper.deleteChild(commentId);
    }

    @Autowired
    private CommentLikeInfoMapper commentLikeInfoMapper;

    @Transactional
    @Override
    public void likeComment(int commentId, int userId) {
        //判断是否点赞过
        CommentLikeInfo commentLikeInfo =commentMapper.selectByUserId(commentId,userId);

        if (commentLikeInfo != null){
            //已经点赞过,抛异常
            throw new LikeNotAllowException("你已经点过赞了");
        }
        // 存入点赞数据  -- 一个修改 一个 新增  事务
        commentMapper.updateCountByCommentId(commentId);
        commentLikeInfoMapper.insertOne(new CommentLikeInfo(null,userId,commentId));
    }

    @Override
    public List<Comment> getCommentList(Integer blogId) {
        //根据parentId分类封装CommentVO
        List<Comment> list=commentMapper.selectList(blogId);
        return formatData(list);
    }
    private List<Comment> formatData(List<Comment> list) {
        ArrayList<Comment> deleteComment = new ArrayList<>();
        // 根据回复对象的id放到对应父评论的list中
        for (Comment comment : list) {
            // 再遍历一次,将parentId == comment.getId()的评论放到comment的list中
            for (Comment c : list) {
                if (comment.getId().equals(c.getParentId())) {
                    if (comment.getList() == null) {
                        comment.setList(new ArrayList<>());
                    }
                    comment.getList().add(c);
                    //原list中删除该评论
                    deleteComment.add(c);
                }
            }
        }
        // 删除原list中回复对象
        list.removeAll(deleteComment);
        return list;
    }

}
